﻿using Abp.Application.Services;
using Sunlit.Business.Policies.Dto;
using Abp.Domain.Repositories;
using System.Linq;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Microsoft.EntityFrameworkCore;
using Sunlit.Business.Dto;
using Sunlit.Business.IO;
using System.IO;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;

namespace Sunlit.Business.Policies
{
    public class PolicyAppService: AsyncCrudAppService<Policy, PolicyDto,long,GetAllPolicyInput,
        CreatePolicyInput,UpdatePolicyInput>,IPolicyAppService
    {
        private readonly IAppFolders _appFolders;
        public PolicyAppService(IRepository<Policy, long> repository,
            IAppFolders appFolders) : base(repository)
        {
            _appFolders = appFolders;
        }
        protected override IQueryable<Policy> CreateFilteredQuery(GetAllPolicyInput input)
        {
            return base.CreateFilteredQuery(input)
                .Include(p=>p.Region)
                .Include(p=>p.PolicyCate)
                .WhereIf(!input.Title.IsNullOrEmpty(), p => p.Title.Contains(input.Title))
                .WhereIf(input.RegionId.HasValue, p => p.RegionId == input.RegionId)
                .WhereIf(input.CreatorUserId.HasValue, p => p.CreatorUserId == input.CreatorUserId)
                .WhereIf(input.PolicyCateId.HasValue, p => p.PolicyCateId == input.PolicyCateId);
        }
        /// <summary>
        /// 更新点击数
        /// </summary>
        /// <param name="input"></param>
        public void UpdateHits(UpdateHitsInput input)
        {
            var article = Repository.FirstOrDefault(c => c.Id == input.ArticleId);
            if (article != null)
            {
                article.Hits += 1;
            }
        }
        public override async Task DeleteAsync(EntityDto<long> input)
        {
            var deleteEntity = await this.GetAsync(input);
            if (!string.IsNullOrWhiteSpace(deleteEntity.ImageUrl))
            {
                var fileNameWithoutExt = Path.GetFileNameWithoutExtension(deleteEntity.ImageUrl);
                var pictureType = fileNameWithoutExt.Split("_").First();
                var userHonorPath = Path.Combine(_appFolders.PictureUpladFolder, pictureType);
                AppFileHelper.DeleteFilesInFolderIfExists(userHonorPath, fileNameWithoutExt);
            }
            await base.DeleteAsync(input);
        }
    }
}
